package com.lzx.iteam;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.lzx.iteam.util.*;
import io.rong.imageloader.core.DisplayImageOptions;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imageloader.core.assist.FailReason;
import io.rong.imageloader.core.listener.SimpleImageLoadingListener;
import io.rong.photoview.PhotoViewAttacher;

import static android.R.id.message;

/**
 * 单张图片显示Fragment
 */
public class ImageDetailFragment extends Fragment {
	public static String mImageUrl;
    public static String mImageThume;
	private ImageView mImageView;
    private ImageView mImageDefault;
	//private ProgressBar progressBar;
	private PhotoViewAttacher mAttacher;
    private int mOrigin;
    private Bitmap mImageBitmap;
    private DisplayImageOptions options;

	public static ImageDetailFragment newInstance(String imageUrl,String thume ,int mOrigin) {

		final ImageDetailFragment f = new ImageDetailFragment();

		final Bundle args = new Bundle();
		args.putString("url", imageUrl);
        args.putString("thume",thume);
        args.putInt("origin",mOrigin);
		f.setArguments(args);

		return f;
        /*if(mFragment == null){
            mFragment = new ImageDetailFragment();
        }
        mImageUrl = imageUrl;
        return  mFragment;*/

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mImageUrl = getArguments() != null ? getArguments().getString("url") : null;
        mImageThume = getArguments().getString("thume");
        mOrigin = getArguments() != null ? getArguments().getInt("origin"):null;
        options = new DisplayImageOptions.Builder()
                .resetViewBeforeLoading(true)
                .delayBeforeLoading(500)
                .cacheInMemory(true)
                .cacheOnDisc(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
	}

    View rootView;
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.image_detail_fragment, container, false);
            mImageView = (ImageView) rootView.findViewById(R.id.image);
            mImageDefault = (ImageView) rootView.findViewById(R.id.image_default);
            mAttacher = new PhotoViewAttacher(mImageView);

            mAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {

                @Override
                public void onPhotoTap(View arg0, float arg1, float arg2) {
                    getActivity().finish();
                    getActivity().overridePendingTransition(0,R.anim.group_back_out);
                }

                @Override
                public void onOutsidePhotoTap() {

                }
            });

            mImageDefault.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getActivity().finish();
                    getActivity().overridePendingTransition(0,R.anim.group_back_out);
                }
            });

            Log.d("info", "onCreateView");
        } else {
            Log.d("info", "rootView != null");
        }
        // Cache rootView.
        // remove rootView from its parent
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
        if (mOrigin == Constants.IMAGE_ORIGIN_URL_ARRAY){
            Log.d("图片下载",mImageUrl);
            ImageLoader.getInstance().displayImage(mImageUrl, mImageView,options, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                    //progressBar.setVisibility(View.VISIBLE);
                    if (!StringUtil.isEmpty(mImageThume)){
                        mImageDefault.setVisibility(View.VISIBLE);
//                        ImageLoader.getInstance().displayImage(mImageThume,mImageDefault,ImageLoaderInterface.optionEventImage);
                        if (mImageThume.startsWith("http")) {
                            ImageLoader.getInstance().displayImage(mImageThume, mImageDefault, ImageLoaderInterface.optionEventImage);
                        } else { // TODO 聊天缩略图是本地
                            String imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + PhotoUtil.FOLDER_IMAGES_THUMBNAILS + mImageThume;
                            ImageLoader.getInstance().displayImage("file://" + imagePath, mImageDefault, ImageLoaderInterface.optionEventImage);
                        }
                    }

                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    String message = "加载出错";
                    if (!NetworkUtil.checkNetwork(getActivity())){
                        message = "网络异常，无法加载";
                    }
                    /*switch (failReason.getType()) {
                        case IO_ERROR:
                            message = "加载出错";
                            break;
                        case DECODING_ERROR:
                            message = "图片无法显示";
                            break;
                        case NETWORK_DENIED:
                            message = "网络异常，无法加载";
                            break;
                        case OUT_OF_MEMORY:
                            message = "图片太大无法显示";
                            break;
                        case UNKNOWN:
                            message = "未知的错误";
                            break;
                        default:
                            message = "加载出错";
                            break;
                    }*/
                    Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                    //progressBar.setVisibility(View.GONE);
                    //mImageDefault.setVisibility(View.GONE);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    //progressBar.setVisibility(View.GONE);
                    mImageDefault.setVisibility(View.GONE);
                    mAttacher.update();
                }
            });
        }else if (mOrigin == Constants.IMAGE_ORIGIN_LOCAL_BASE){ // base64压缩的图片
            byte[] image = StringUtil.decompressToByteArrayByGzip(mImageUrl);
            if(image!=null){
            mImageBitmap = BitmapFactory.decodeByteArray(image, 0, image.length);}
            mImageView.setImageBitmap(mImageBitmap);
        }else if (mOrigin == Constants.IMAGE_ORIGIN_LOCAL_STRING || mOrigin == Constants.IMAGE_ORIGIN_LOCAL_ARRAY ){ // 图片的本地地址
            if(!"".equals(mImageUrl)){
                mImageBitmap = PhotoUtil.readBitmapFromPath(getActivity(), mImageUrl,true);
                if(mImageBitmap == null){
                    Toast.makeText(getActivity(),"获取图片失败",Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                    return;
                }
                /*int degree = PhotoUtil.getExifOrientation(mImageUrl);
                if(degree != 0){
                    mImageBitmap = PhotoUtil.rotaingImageView(mImageBitmap,degree);
                }*/
                mImageView.setImageBitmap(mImageBitmap);
            }
        }
	}

}
